<template>
	<view class="page">
		<scroll-view class="scroll-view" scroll-y scroll-with-animation :scroll-top="top" @scrolltoupper="loadMoreMessages">
					<view style="padding: 30rpx 30rpx 240rpx;">
			<!-- 加载更多提示 -->
			<view v-if="isLoading" class="loading-tip">
				<text>加载中...</text>
			</view>
			<view v-else-if="!hasMore && list.length > 0" class="loading-tip">
				<text>没有更多消息了</text>
			</view>
			
			<view class="message" :class="[item.userType]" v-for="(item,index) in list" :key="index"
				@click="msgClick(item)">
				<image :src="item.avatar" v-if="item.userType === 'friend'" class="avatar" mode="widthFix"></image>
				<view class="content" v-if="item.messageType === 'image'">
					<image :src="item.content" mode="widthFix"></image>
				</view>
				<view class="content" v-else-if="item.messageType === 'video'">
					<video :src="item.content" class="video-message" controls></video>
				</view>
				<view class="content" v-else>
					{{ item.content }}
				</view>
				<image :src="item.avatar" v-if="item.userType === 'self'" class="avatar" mode="widthFix"></image>
			</view>
		</view>
		</scroll-view>

		<view class="tool">
			<image src="https://www.shuyunpt.com/app/image/notice/image.png" mode="widthFix" class="left-icon" @click="chooseImage"></image>
			<image src="https://www.shuyunpt.com/app/image/notice/video.png" mode="widthFix" class="left-icon" @click="chooseVideo"></image>
			<input type="text" v-model="content" class="input" @confirm="send" placeholder="请输入发送的内容"/>
			<button class="send-btn" @click="send" :disabled="!content.trim()">发送</button>
		</view>

	</view>
</template>

<script>
	import { baseUrl } from '@/utils/config.js'
	
	export default {
		data() {
			return {
				content: '',
				list: [],
				top: 0,
				message_id:"",
				timer:null,
				// 分页相关
				page: 1,
				pageSize: 20,
				hasMore: true,
				isLoading: false,
				isFirstLoad: true // 标记是否首次加载
			};
		},
		onUnload() {
			clearInterval(this.timer)
		},
		onLoad(options) {
			uni.setNavigationBarTitle({
				title: options.name
			})
			this.message_id = options.message_id
			this.getInfo(options.message_id)
			// 重置分页参数
			this.page = 1;
			this.hasMore = true;
			this.getChatRecordList(options.message_id)
			this._selfAvatar = this.getSelfAvatar()
			this.timer = setInterval(()=>{
				this.getNewRecordList()
			},5000)
		},
		onShow() {
			// 页面显示时更新个人头像
			this._selfAvatar = this.getSelfAvatar();
		},
		
		onHide() {
			if (this._innerAudioContext) {
				this._innerAudioContext.stop()
			}
		},
		methods: {
			// 获取个人头像
			getSelfAvatar() {
				// 从store中获取用户信息
				const userInfo = this.$store.state.qxInfo;
				if (userInfo && userInfo.avatar) {
					return userInfo.avatar;
				}
				
				// 从本地缓存获取用户信息
				const cachedUserInfo = uni.getStorageSync('qxInfo');
				if (cachedUserInfo && cachedUserInfo.avatar) {
					return cachedUserInfo.avatar;
				}
				
				// 默认头像
				return 'https://www.shuyunpt.com/app/image/default-avatar.png';
			},
			
			async getInfo(message_id){
				const res = await this.$service({
					url:"/api/member.message/getMessageDetail",
					data:{
						message_id
					}
				})
				console.log(res);
				this._friendAvatar = res.data.avatar
			},
			async getChatRecordList(message_id, isLoadMore = false){
				if (this.isLoading) return;
				
				this.isLoading = true;
				
				try {
					const res = await this.$service({
						url:"/api/member.message/getChatRecordList",
						data:{
							message_id,
							page: this.page,
							page_size: this.pageSize
						}
					})
					console.log(res);
					
					if (res.code == 1) {
						const newMessages = res.data.map(item=>{
							return{
								content: item.content,
								userType: item.is_self == 0 ? 'friend' : 'self',
								messageType: item.type == 1 ? 'text' : item.type == 2 ? 'image' : item.type == 3 ? 'video' : 'text',
								avatar: item.is_self == 0 ? this._friendAvatar : this._selfAvatar
							}
						});
						
						if (isLoadMore) {
							// 加载更多时，将新消息插入到列表前面
							this.list.unshift(...newMessages);
						} else {
							// 首次加载时，直接替换列表
							this.list = newMessages;
						}
						
						// 判断是否还有更多数据
						this.hasMore = newMessages.length >= this.pageSize;
						
						console.log(this.list);
						
						// 首次加载完成后，滚动到底部
						if (this.isFirstLoad && !isLoadMore) {
							this.$nextTick(() => {
								this.scrollToBottomPrecise();
								this.isFirstLoad = false;
							});
						}
					} else {
						this.$hint.desc(res.msg || '获取聊天记录失败');
					}
				} catch (error) {
					console.error('获取聊天记录失败:', error);
					this.$hint.desc('获取聊天记录失败');
				} finally {
					this.isLoading = false;
				}
			},
			// 加载更多历史消息
			async loadMoreMessages() {
				if (!this.hasMore || this.isLoading) {
					return;
				}
				
				// 记录当前滚动位置
				const currentScrollTop = this.top;
				
				// 增加页码
				this.page++;
				
				// 加载更多消息
				await this.getChatRecordList(this.message_id, true);
				
				// 保持滚动位置，避免页面跳动
				this.$nextTick(() => {
					this.top = currentScrollTop;
				});
			},
			
			async getNewRecordList(){
				const res = await this.$service({
					url:"/api/member.message/getNewRecordList",
					data:{
						message_id:this.message_id,
					}
				})
				if(res.code == 1)
				{
					let data = res.data.map(item=>{
						return{
							content: item.content,
							userType: item.is_self == 0 ? 'friend' : 'self',
							messageType: item.type == 1 ? 'text' : item.type == 2 ? 'image' : item.type == 3 ? 'video' : 'text',
							avatar: item.is_self == 0 ? this._friendAvatar : this._selfAvatar
						}
					})
					if (data.length > 0) {
						this.list.push(...data);
						// 收到新消息时自动滚动到底部
						this.$nextTick(() => {
							this.scrollToBottom();
						});
					}
				}
				// console.log(res);
				
				
				
			},
			async send() {
				// 检查输入内容是否为空
				if (!this.content.trim()) {
					this.$hint.desc('请输入发送内容');
					return;
				}

				const res = await this.$service({
					url:"/api/member.message/sendMessage",
					data:{
						message_id:this.message_id,
						content:this.content
					}
				})
				console.log(res)
				if(res.code == 1){
					this.list.push({
						content: this.content,
						userType: 'self',
						avatar: this._selfAvatar
					})
					this.content = ''
					// 发送消息后滚动到底部
					this.$nextTick(() => {
						this.scrollToBottom();
					});
				}else{
					this.$hint.desc(res.msg)
				}
			},

			async chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFilePath = res.tempFilePaths[0];
						
						try {
							// 显示上传中提示
							this.$hint.showLoading('发送中...');
							
							// 上传图片到服务器
							const uploadRes = await uni.uploadFile({
								url: baseUrl + '/api/common/uploadImg',
								filePath: tempFilePath,
								name: 'images',
								header: {
									'Authorization': uni.getStorageSync('token') || ''
								}
							});
							
							const result = JSON.parse(uploadRes.data);
							
							if (result.code == 1) {
								// 发送图片消息
								const sendRes = await this.$service({
									url: "/api/member.message/sendMessage",
									data: {
										message_id: this.message_id,
										content: result.data.url,
										type: 2
									}
								});
								
								if (sendRes.code == 1) {
									// 添加到消息列表
									this.list.push({
										content: result.data.url,
										userType: 'self',
										messageType: 'image',
										avatar: this._selfAvatar
									});
									// 发送图片后滚动到底部
									this.$nextTick(() => {
										this.scrollToBottom();
									});
								} else {
									this.$hint.desc(sendRes.msg || '发送失败');
								}
							} else {
								this.$hint.desc(result.msg || '图片上传失败');
							}
						} catch (error) {
							console.error('发送图片失败:', error);
							this.$hint.desc('发送图片失败，请重试');
						} finally {
							this.$hint.hideLoading();
						}
					}
				});
			},

			async chooseVideo() {
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60, // 最大时长60秒
					camera: 'back',
					success: async (res) => {
						const tempFilePath = res.tempFilePath;
						
						// 检查视频时长
						if (res.duration > 60) {
							this.$hint.desc('视频时长不能超过60秒');
							return;
						}
						
						// 检查视频大小（限制为50MB）
						if (res.size > 50 * 1024 * 1024) {
							this.$hint.desc('视频大小不能超过50MB');
							return;
						}
						
						try {
							// 显示上传中提示
							this.$hint.showLoading('发送中...');
							
							// 上传视频到服务器
							const uploadRes = await uni.uploadFile({
								url: baseUrl + '/api/common/uploadVideo',
								filePath: tempFilePath,
								name: 'video',
								header: {
									'Authorization': uni.getStorageSync('token') || ''
								}
							});
							
							const result = JSON.parse(uploadRes.data);
							
							if (result.code == 1) {
								// 发送视频消息
								const sendRes = await this.$service({
									url: "/api/member.message/sendMessage",
									data: {
										message_id: this.message_id,
										content: result.data.url,
										type: 3
									}
								});
								
								if (sendRes.code == 1) {
									// 添加到消息列表
									this.list.push({
										content: result.data.url,
										userType: 'self',
										messageType: 'video',
										avatar: this._selfAvatar
									});
									// 发送视频后滚动到底部
									this.$nextTick(() => {
										this.scrollToBottom();
									});
								} else {
									this.$hint.desc(sendRes.msg || '发送失败');
								}
							} else {
								this.$hint.desc(result.msg || '视频上传失败');
							}
						} catch (error) {
							console.error('发送视频失败:', error);
							this.$hint.desc('发送视频失败，请重试');
						} finally {
							this.$hint.hideLoading();
						}
					}
				});
			},

			scrollToBottom() {
				// 使用更大的值确保滚动到底部
				this.top = this.list.length * 2000;
				
				// 延迟执行，确保DOM更新完成
				setTimeout(() => {
					this.top = this.list.length * 2000;
				}, 100);
			},
			
			// 更精确的滚动到底部方法
			scrollToBottomPrecise() {
				// 使用 nextTick 确保 DOM 更新完成
				this.$nextTick(() => {
					// 计算所有消息的高度
					const messageHeight = 120; // 每条消息大约高度
					const totalHeight = this.list.length * messageHeight;
					this.top = totalHeight + 1000; // 额外添加一些高度确保滚动到底部
					
					// 再次延迟执行，确保滚动生效
					setTimeout(() => {
						this.top = totalHeight + 1000;
					}, 50);
				});
			},

			msgClick(data) {
				if (data.messageType === 'image') {
					// 预览图片
					uni.previewImage({
						urls: [data.content],
						current: data.content
					});
				} else if (data.messageType === 'video') {
					// 播放视频
					//uni.navigateTo({
					//	url: `/pages/common/video-player?url=${encodeURIComponent(data.content)}`
					//});
				}
			},


		}
	}
</script>

<style lang="scss" scoped>
	.scroll-view {
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		background: #eee;
		box-sizing: border-box;
	}

	.loading-tip {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	.message {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 10rpx;
			margin-right: 30rpx;
		}

		.content {
			min-height: 80rpx;
			max-width: 60vw;
			box-sizing: border-box;
			font-size: 28rpx;
			line-height: 1.3;
			padding: 20rpx;
			border-radius: 10rpx;
			background: #fff;

			image {
				max-width: 400rpx;
				max-height: 400rpx;
				border-radius: 8rpx;
			}
			
			.video-message {
				max-width: 400rpx;
				max-height: 300rpx;
				border-radius: 8rpx;
				background-color: #000;
			}
		}

		&.self {
			justify-content: flex-end;

			.avatar {
				margin: 0 0 0 30rpx;
			}

			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-left: 16rpx solid #fff;
					right: -28rpx;
					top: 24rpx;
				}
			}
		}

		&.friend {
			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-right: 16rpx solid #fff;
					left: -28rpx;
					top: 24rpx;
				}
			}
		}
	}

	.tool {
		position: fixed;
		width: 100%;
		min-height: 120rpx;
		left: 0;
		bottom: 0;
		background: #fff;
		display: flex;
		align-items: flex-start;
		box-sizing: border-box;
		padding: 20rpx 24rpx 20rpx 40rpx;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)/2) !important;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom)/2) !important;
		.left-icon {
			width: 56rpx;
			height: 56rpx;
			margin-right: 10rpx;
		}

		.input,
		.voice-crl {
			background: #eee;
			border-radius: 10rpx;
			height: 70rpx;
			margin-right: 30rpx;
			flex: 1;
			padding: 0 20rpx;
			box-sizing: border-box;
			font-size: 28rpx;
		}

		.thumb {
			width: 64rpx;
			height: 64rpx;
		}

		.send-btn {
			width: 120rpx;
			height: 70rpx;
			background: #5C65FF;
			color: #fff;
			border: none;
			border-radius: 10rpx;
			font-size: 28rpx;
			font-weight: bold;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.send-btn:disabled {
			background: #ccc;
			color: #999;
		}

		.send-btn::after {
			border: none;
		}
	}


</style>